//
//  RHNetworkConfigInfoVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/1.
//

#import "RHNetworkConfigInfoVC.h"
#import "RHNetworkConfigResultVC.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "DevSocketManage.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <NetworkExtension/NetworkExtension.h>

@interface RHNetworkConfigInfoVC ()
@property (nonatomic, strong) QMUITextField *idTextField;

@property (nonatomic, strong) QMUITextField *typeTextField;

@property (nonatomic, strong) QMUITextField *ssidTextField;

@property (nonatomic, strong) QMUITextField *pwdTextField;

@property (nonatomic, strong) QMUITextField *ipTf;
@property (nonatomic, strong) QMUITextField *portTf;

@property (nonatomic ,copy) NSString *ssid;
@end

@implementation RHNetworkConfigInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"配网".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self checkIsWIFI];
}
/*
 1.连接WIFI,获取要发送给设备配网的WIFI名称
 2.连接设备热点,发送配网指令
 
 */


#pragma mark ------  判断当前是否连接WIFI

-(void)checkIsWIFI{

    if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi){
        //获取WIFI名称
        NSString *ssid = [self getSSID];
        self.ssid = ssid;
        self.ssidTextField.text = ssid;
        NSLog(@"----->当前WIFI名称:%@",ssid);
        
       
        //获取IP地址,测试用
        [self getNetworkAddressDetailHandler:^(NSString *interface, NSString *address, NSString *addressType) {
            NSLog(@"---->%@\n---->%@\n---->%@",interface,address,addressType);
            self.ipTf.text = @"192.168.0.121";
            self.portTf.text = @"8082";
        }];
       
        
    }else{
        NSString *urlString = @"App-Prefs:root=WIFI";
        NSURL *url = [NSURL URLWithString:urlString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                    
                }];
            }
        }
    }
}

#pragma mark ------ 获取WIFI名称
-(NSString *)getSSID
{
    NSString *ssid = @"";
    CFArrayRef arrRef = CNCopySupportedInterfaces();
    NSArray *ifs = (__bridge id)arrRef;
    for (NSString *ifnam in ifs) {
        CFDictionaryRef dicRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSDictionary *info = (__bridge id)dicRef;
        if (info[@"BSSID"]) {
            ssid = info[@"SSID"];
        }
        if(dicRef !=nil) {
            CFRelease(dicRef);
        }
    }
    if(arrRef != nil) {
        CFRelease(arrRef);
    }
    return ssid;
}
//获取地址结构体对象，并遍历
- (NSString *)getNetworkAddressDetailHandler:(void(^)(NSString *interface, NSString *address, NSString *addressType))handler
{
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0) {
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            [self getAddress:temp_addr handler:handler];
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return nil;
}
/**
 地址类型释义    temp_addr->ifa_name
 lo     本地回环 (Loopback)
 en     无线网 (WiFi)
 pdp_ip 蜂窝网络 (Cellular)
 awdl   通信Wi-Fi (Apple Wireless Direct Link，用于AirDrop、AirPlay、GameKit 和 Apple Pencil )
 utun   虚拟隧道 (VPN)
 ipsec  虚拟隧道 (VPN)
 llw    低延迟无线局域网（Low-latency WLAN）
 */

//处理单个地址对象
- (void)getAddress:(struct ifaddrs *)temp_addr handler:(void(^)(NSString *interface, NSString *address, NSString *addressType))handler
{
    // 网络地址族
    sa_family_t sa_family = temp_addr->ifa_addr->sa_family;
    // 网络接口
    NSString *interface;
    // 网络地址
    NSString *address;
    // 网络地址
    NSString *addressType;
    // IPv4
    if(sa_family == AF_INET){
        interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
        struct sockaddr_in *ifa_addr = ((struct sockaddr_in *)temp_addr->ifa_addr);
        address = [NSString stringWithUTF8String:inet_ntoa(ifa_addr->sin_addr)];
        addressType = @"IPv4";
    }
    // IPv6
    else if (sa_family == AF_INET6){
        interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
        struct sockaddr_in6 *ifa_addr = ((struct sockaddr_in6 *)temp_addr->ifa_addr);
        char buf[INET6_ADDRSTRLEN] = {0};
        const char *ipv6 = inet_ntop(AF_INET6, &ifa_addr->sin6_addr, buf, sizeof(buf));
        address = [NSString stringWithUTF8String:ipv6];
        addressType = @"IPv6";
    }
    if (interface.length && handler){
        if([address hasPrefix:@"192.168"]){
            handler(interface, address, addressType);
        }
       
    }
}

#pragma mark ------ 连接设备热点

-(void)connectDeviceHotWithDeviceId:(NSString *)deviceId
{
    //TP-LINK B0F3      Zruipower2016!
    //TP-LINK_5G_B0F3   Zruipower2016!
    //Laboratory-5G     lab2303!
    //Laboratory     lab2303!
    //Laboratory-Y5G     lab2303s
    NSString *ssid = @"Laboratory";
    NSString *password = @"lab2303!";
    NSString *currentWIFI = [self getSSID];
    //如果已连接热点
    if([currentWIFI isEqualToString:ssid]){
        
        [self connectDeviceSocket];
    }else{
        [QMUITips showLoading:@"连接设备热点...".rh_localized inView:self.view];
        
        NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:ssid passphrase:password isWEP:NO];
        hotspotConfig.joinOnce = YES;
        // 开始连接 (调用此方法后系统会自动弹窗确认)
        [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
            [QMUITips hideAllToastInView:self.view animated:YES];
            if(!error){
                NSLog(@"已连接");
                NSString *currentWIFI = [self getSSID];
                if([currentWIFI isEqualToString:ssid]){
                    
                    //刚连接上设备热点,1秒后再连socket
                    [QMUITips showLoadingInView:self.view];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [QMUITips hideAllToastInView:self.view animated:YES];
                        //连接设备热点成功,连接socket
                        [self connectDeviceSocket];
                    });
                    
                }else{
                    //加入失败,跳转到到系统WIFI设置页面
                    [self jumpToSetWifi];
                }
            
                NSLog(@"---->当前连接的WIFI:%@",[self getSSID]);
//                [[NEHotspotConfigurationManager sharedManager] getConfiguredSSIDsWithCompletionHandler:^(NSArray<NSString *> * array) {
//                        for (NSString * str in array) {
//                            NSLog(@"加入过的WiFi：%@",str);
//
//                        }
//                }];
            }else if (error && error.code != 13 && error.code != 7) {
                NSLog(@"加入失败");
            }else if(error.code ==7){
                NSLog(@"已取消");
            }else{
                NSLog(@"其他原因");
            }
            NSLog(@"---->错误信息:%@",error);
        }];
            
      
        
    }
    
}

//跳转系统WIFI设置页面
- (void)jumpToSetWifi{
    NSString *urlString = @"App-Prefs:root=WIFI";
    NSURL *url = [NSURL URLWithString:urlString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
//                self.isToSetWifi = YES;
            }];
        }
    }
}


#pragma mark ------ 连接设备socket
-(void)connectDeviceSocket
{
    [[DevSocketManage shareSocketManage]connectToHost:self.ipTf.text onPort:[self.portTf.text integerValue] result:^(BOOL isConnect) {
        if(isConnect){
            NSLog(@"---->连接设备socket成功1 IP:%@ 端口:%@",self.ipTf.text,self.portTf.text);
            NSString *countrCode = [UserDefaults objectForKey:kRegionCode];
            NSString *message = [NSString stringWithFormat:@"-WIFICONFIG:%@,%@,%@",self.ssidTextField.text,self.pwdTextField.text,countrCode];
            [[DevSocketManage shareSocketManage]sendMessage:message];
            RHNetworkConfigResultVC *netstatusVC = [[RHNetworkConfigResultVC alloc]init];
            netstatusVC.deviceId = self.deviceId;
            netstatusVC.password = self.password;
            netstatusVC.lastSSID = self.ssidTextField.text;
            netstatusVC.ssidPWD = self.pwdTextField.text;
            [self.navigationController pushViewController:netstatusVC animated:YES];
        }else{
            NSLog(@"---->连接设备socket失败1:%@ 端口:%@",self.ipTf.text,self.portTf.text);
        }
    }];
}


#pragma mark ----- 配网
-(void)configNetwork
{
    if(self.deviceId.length == 0){
        [QMUITips showError:@"请输入设备ID".rh_localized];
        return;
    }
    
    if(self.ssidTextField.text.length == 0){
        [QMUITips showError:@"请输入WiFi名称".rh_localized];
        return;
    }
    if(self.pwdTextField.text.length == 0){
        [QMUITips showError:@"请输入WiFi密码".rh_localized];
        return;
    }
    [self connectDeviceHotWithDeviceId:self.deviceId];

}

-(void)setupUI{
    UIView *bgView = kView;
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(20, 20, 20, 20));
    }];
    
    
    
    QMUILabel *idTitleLab = [[QMUILabel alloc]init];
    idTitleLab.text = [NSString stringWithFormat:@"%@:",@"设备ID".rh_localized];
    idTitleLab.textColor = kCOLOR_HEX(@"3F4443");
    idTitleLab.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:idTitleLab];
    
    kWeakSelf;
   
    

    _idTextField = [[QMUITextField alloc]init];
    _idTextField.text = self.deviceId;
    _idTextField.userInteractionEnabled = NO;
    [bgView addSubview:_idTextField];
    [_idTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(idTitleLab.mas_right).offset(15);
        make.centerY.equalTo(idTitleLab);
        make.height.offset(40);
        make.right.mas_offset(-10);
        make.width.greaterThanOrEqualTo(@(20));
    }];
    
    UIView *line = kView;
    [bgView addSubview:line];
    line.backgroundColor = CFCellLineColor;
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(idTitleLab);
        make.right.equalTo(weakSelf.idTextField);
        make.height.offset(1);
        make.top.equalTo(weakSelf.idTextField.mas_bottom).offset(1);
    }];
    
    
    
    QMUILabel *wifiTitleLab = [[QMUILabel alloc]init];
    wifiTitleLab.text = @"设备类型:".rh_localized;
    wifiTitleLab.textColor = kCOLOR_HEX(@"3F4443");
    wifiTitleLab.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:wifiTitleLab];
    
    
    
    _typeTextField = [[QMUITextField alloc]init];
    _typeTextField.text = self.deviceType;
    _typeTextField.userInteractionEnabled = NO;
    [bgView addSubview:_typeTextField];
    [_typeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifiTitleLab.mas_right).offset(15);
        make.centerY.equalTo(wifiTitleLab);
        make.height.offset(40);
        make.right.equalTo(weakSelf.idTextField);
    }];
    
    UIView *line2 = kView;
    [bgView addSubview:line2];
    line2.backgroundColor = CFCellLineColor;
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifiTitleLab);
        make.right.equalTo(weakSelf.typeTextField);
        make.height.offset(1);
        make.top.equalTo(weakSelf.typeTextField.mas_bottom).offset(1);
    }];
    
    
    QMUILabel *wifi_2TitleLab = [[QMUILabel alloc]init];
    wifi_2TitleLab.text = [NSString stringWithFormat:@"%@:",@"WiFi名称".rh_localized];
    wifi_2TitleLab.textColor = kCOLOR_HEX(@"3F4443");
    wifi_2TitleLab.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:wifi_2TitleLab];
    
    
    
    _ssidTextField = [[QMUITextField alloc]init];
    _ssidTextField.placeholder = @"请输入WiFi名称".rh_localized;
    [bgView addSubview:_ssidTextField];
    [_ssidTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifi_2TitleLab.mas_right).offset(15);
        make.centerY.equalTo(wifi_2TitleLab);
        make.height.offset(40);
        make.right.equalTo(weakSelf.idTextField);
    }];
    
    UIView *line3 = kView;
    [bgView addSubview:line3];
    line3.backgroundColor = CFCellLineColor;
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifiTitleLab);
        make.right.equalTo(weakSelf.typeTextField);
        make.height.offset(1);
        make.top.equalTo(weakSelf.ssidTextField.mas_bottom).offset(1);
    }];
    
    
    QMUILabel *pwdTitleLab = [[QMUILabel alloc]init];
    pwdTitleLab.text = [NSString stringWithFormat:@"%@:",@"WiFi密码:".rh_localized];
    pwdTitleLab.textColor = kCOLOR_HEX(@"3F4443");
    pwdTitleLab.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:pwdTitleLab];
    
    
    
    _pwdTextField = [[QMUITextField alloc]init];
    _pwdTextField.placeholder = @"请输入密码".rh_localized;
    _pwdTextField.text = @"fdf456";
    [bgView addSubview:_pwdTextField];
    [_pwdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwdTitleLab.mas_right).offset(15);
        make.centerY.equalTo(pwdTitleLab);
        make.height.offset(40);
        make.right.equalTo(weakSelf.idTextField);
    }];
    
    UIView *line4 = kView;
    [bgView addSubview:line4];
    line4.backgroundColor = CFCellLineColor;
    [line4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifiTitleLab);
        make.right.equalTo(weakSelf.typeTextField);
        make.height.offset(1);
        make.top.equalTo(weakSelf.pwdTextField.mas_bottom).offset(1);
    }];
    
    _ipTf = [[QMUITextField alloc]init];
    [_ipTf setBorderStyle:UITextBorderStyleRoundedRect];
    _ipTf.placeholder = @"IP";
    [bgView addSubview:_ipTf];
    [_ipTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.top.equalTo(line4.mas_bottom).offset(30);
        make.height.offset(40);
        make.right.offset(-30);
    }];
    
    _portTf = [[QMUITextField alloc]init];
    [_portTf setBorderStyle:UITextBorderStyleRoundedRect];
    _portTf.placeholder = @"Port";
    [bgView addSubview:_portTf];
    [_portTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.top.equalTo(_ipTf.mas_bottom).offset(30);
        make.height.offset(40);
        make.right.offset(-30);
    }];
    
    
    CGFloat title_width = 0;
    [idTitleLab sizeToFit];
    [wifiTitleLab sizeToFit];
    [wifi_2TitleLab sizeToFit];
    [pwdTitleLab sizeToFit];
    title_width = MAX(title_width, idTitleLab.width);
    title_width = MAX(title_width, wifiTitleLab.width);
    title_width = MAX(title_width, wifi_2TitleLab.width);
    title_width = MAX(title_width, pwdTitleLab.width);
    title_width +=1;
    [idTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.top.mas_offset(40);
            make.width.mas_offset(title_width);
    }];
    
    [wifiTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(idTitleLab);
            make.top.equalTo(line.mas_bottom).offset(20);
        make.width.mas_offset(title_width);
    }];
    
    [wifi_2TitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(idTitleLab);
            make.top.equalTo(line2.mas_bottom).offset(20);
        make.width.mas_offset(title_width);
    }];
    
    [pwdTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(idTitleLab);
            make.top.equalTo(line3.mas_bottom).offset(20);
        make.width.mas_offset(title_width);
    }];

    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.backgroundColor = CMainColorGreen;
    sureBtn.layer.cornerRadius = 8;
    sureBtn.layer.masksToBounds = YES;
    [sureBtn addTarget:self action:@selector(configNetwork) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:sureBtn];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.right.mas_offset(-20);
            make.bottom.mas_offset(-20);
            make.height.offset(kScaleW(45));
    }];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
